#!/usr/bin/env python
# --coding:utf-8--
"""
@Author  : cpl
"""


import requests
import json
import semver as sv
import os
import GlobalVar

class npm_VersionUtils:
    def __init__(self):
        self.url = 'https://registry.npmjs.org/'
        self.root_path = './projects/'
        self.name = ''
        self.version = ''
        self.pkg_json = ''

    def set_name_version(self, name, version=''):
        self.name = name
        self.version = version

    def load_pkgjson(self):
        cur_path = self.root_path+self.name+'.json'
        if os.path.isfile(cur_path):

            f = open(cur_path, 'r')
            content = f.read()
            self.pkg_json = json.loads(content)
            # print("file exist：",type(a))
            f.close()

        else:
            self.pkg_json = self.rquest_pkgjson()
            if 'error' in self.pkg_json:
                return self.pkg_json 
            write_data = json.dumps(self.pkg_json)
            os.makedirs(os.path.dirname(cur_path), exist_ok=True)
            f = open(cur_path, 'w')
            f.write(write_data)
            # print("add new file: ", cur_path)
            f.close()
        return self.pkg_json

    def rquest_pkgjson(self):
        url = self.url + self.name
        # self.pkg_json = requests.get(url).json()

        try:
            # self.pkg_json = requests.get(url).json() # 网络原因？使用requests访问卡死，而直接浏览器访问快速返回，使用curl也是
            r = os.popen('curl -s %s' % url).readlines() # -s是静音模式，命令行不会输出curl的执行信息
            if len(r) == 0:
                self.pkg_json.status_code = "URL error"
                GlobalVar.add_miss(self.name, 403)
                return {"error": "Page not found"}

            self.pkg_json = json.loads(r[0])

        except:
            self.pkg_json.status_code = "Command error"
            GlobalVar.add_miss(self.name, 403)
            return {"error": "Command error"}


        if "error" in self.pkg_json or "_id" not in self.pkg_json:
            GlobalVar.add_miss(self.name, 404)
            return {"error": "Package %s IS Not Found!"%(self.name)}
        else:
            return self.pkg_json

    def getverlist(self):
        verinfo = list(self.pkg_json['versions'].keys())
        return verinfo

    def satisfiedVerions(self, range):
        vers = []
        verlist = self.getverlist()
        for v in verlist:
            if sv.satisfies(v, range, loose=True, include_prerelease=True):
                vers.append(v)
        return vers

    def max_satisfied(self):
        if self.version == 'latest':
            if 'dist-tags'in self.pkg_json.keys() and 'latest' in self.pkg_json['dist-tags'].keys():
                return self.pkg_json['dist-tags']['latest']
            else:
                if 'versions' in self.pkg_json.keys():
                    # print("-%s %s- has no 'dist-tags' or 'latest' tag, using the last one!"%(self.name, self.version))
                    return list(self.pkg_json['versions'].keys())[-1]
                else:
                    GlobalVar.add_noversionPkg(self.name, "has no 'versions' tag for: %s" % (self.version))
                    # print("-%s %s- has no 'versions' tag!"%(self.name, self.version))
                    return None
        elif 'versions' in self.pkg_json.keys():
            verinfo = list(self.pkg_json['versions'].keys())
            select_v = sv.max_satisfying(verinfo, self.version)
            if select_v == None:
                GlobalVar.add_noversionPkg(self.name, "has no version satisfied for: %s" % (self.version))
                # print("-%s- has no version satisfied for %s!"%(self.name, self.version))
            return select_v
        else:
            GlobalVar.add_noversionPkg(self.name, "has no 'versions' tag for: %s" % (self.version))
            # print("-%s %s- has no 'versions' tag!"%(self.name, self.version))
            return None

